import {
    request,
    AbstractBookCrawler,
    BasicBook,
    SearchBookResult,
    Book,
    BasicChapter,
    BookCrawlerTest,
    BookSource,
    htmlToString,
    removeQuerySelector,
    getPathFromUrl,
} from "../../common/common_node.js";

class BookCrawler extends AbstractBookCrawler {

    async searchBook(keyword, pageNum) {

        const $ = await (await request(`${this.source.searchBaseUrl}/modules/article/search.php?q=${keyword}`)).doc();
        const trArr = $("table.grid tr#nr");
        const bookArr = [];
        trArr.each(function (i, e) {
            const bookName = $(e).find(".odd a");
            bookArr.push(new BasicBook({
                name: bookName.text(),
                author: $(e).find(".odd").eq(1).text(),
                path: getPathFromUrl(bookName.attr("href")),
            }));
        })

        return new SearchBookResult({
            pageNum: pageNum,
            pages: 1,
            keyword: keyword,
            bookList: bookArr
        });
    }

    async bookDetails(path) {

        const $ = await (await request(this.source.bookBaseUrl + path)).doc();
        return new Book({
            sourceId: this.source.id,
            path: path,
            name: $('[property="og:novel:book_name"]').attr("content"),
            author: $('[property="og:novel:author"]').attr("content"),
            intro: $('[property="og:description"]').attr("content"),
            coverUrl: $('[property="og:image"]').attr("content"),
            type: $('[property="og:novel:category"]').attr("content"),
        });
    }

    async bookCatalog(path) {

        const $ = await (await request(this.source.bookBaseUrl + path)).doc();
        const chapters = $('#list dl dd a');
        let catalog = [];
        chapters.each(function (i, e) {
            const item = $(e);
            catalog.push(new BasicChapter({
                index: i,
                title: item.text(),
                path: item.attr("href")
            }));
        });
        return catalog;
    }

    async chapterContent(path) {

        const $ = await (await request(this.source.bookBaseUrl + path)).doc();
        const contentElement = removeQuerySelector($("#content"), ["#content_tip"]);
        return htmlToString(contentElement.html());
    }
}

const source = {
    "id": "free_book_js/20",
    "name": "00小说网",
    "portalUrl": "https://www.00shu.la",
    "searchBaseUrl": "https://www.00shu.la",
    "bookBaseUrl": "https://www.00shu.la",
    "active": true
};

await new BookCrawlerTest(new BookCrawler(BookSource.createTestBookSource(source)), {
    enableSearch: true, keyword: "大明国师"
}).run();

